// src/hooks/useDialog.js
import { ref } from 'vue'
import { QDialog, QCard, QCardSection, QCardActions, QBtn } from 'quasar'
import { h, createApp } from 'vue'

// 默认的对话框组件
const DefaultDialog = {
  props: {
    title: String,
    content: String,
  },
  setup(props) {
    return () =>
      h(QCard, {}, [
        props.title && h(QCardSection, {}, () => h('div', { class: 'text-h6' }, props.title)),
        h(QCardSection, {}, () => props.content),
        h(QCardActions, { align: 'right' }, () => [
          h(QBtn, {
            flat: true,
            label: '确定',
            color: 'primary',
            'v-close-popup': true,
          }),
        ]),
      ])
  },
}

export function useDialog() {
  const dialogInstance = ref(null)

  const open = (componentOrOptions, props = {}) => {
    let component
    let componentProps

    // 判断第一个参数是组件还是配置对象
    if (
      typeof componentOrOptions === 'object' &&
      !componentOrOptions.render &&
      !componentOrOptions.setup
    ) {
      // 如果是配置对象，使用默认对话框组件
      component = DefaultDialog
      componentProps = componentOrOptions
    } else {
      // 如果是自定义组件，使用传入的组件和props
      component = componentOrOptions
      componentProps = props
    }

    const dialogVNode = h(
      QDialog,
      {
        modelValue: true,
        onHide: () => {
          dialogInstance.value = null
        },
      },
      {
        default: () => h(component, componentProps),
      },
    )

    const app = createApp(dialogVNode)
    dialogInstance.value = app.mount(document.body)

    return dialogInstance.value
  }

  const close = () => {
    if (dialogInstance.value) {
      dialogInstance.value.unmount()
      dialogInstance.value = null
    }
  }

  return {
    open,
    close,
  }
}
